package com.atao.baokede.utils;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class OrderIdUtil {
    @Autowired
    private RedisTemplate redisTemplate;

    // 静态变量用于在静态方法中访问
    private static RedisTemplate staticRedisTemplate;

    //订单编号生成，订单编号生成规则：当前时间（精确到毫秒），如2025年1月2日13时14分15秒，
    // 随后五位则从00001到99999递增，用redis记录当天的五位数的递增，次日刷新，从00001开始
    // 则订单编号生成为2025010213141500001-2025010213141599999
    @PostConstruct
    public void init() {
        staticRedisTemplate = this.redisTemplate;
    }

    public static String generateOrderId() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String frontOrderId = sdf.format(new Date());
        Object value = staticRedisTemplate.opsForValue().get("lastOrderId");
        String lastOrderId = "";
        int a = Integer.parseInt((String) value);
        // 格式化为5位数
        lastOrderId = String.format("%011d", a);
        a++;
        staticRedisTemplate.opsForValue().set("lastOrderId", String.valueOf(a));
        return frontOrderId + lastOrderId;
    }
}